package com.exwave.socialgame.model_websocket;


import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import lombok.extern.slf4j.Slf4j;

/**
 * @ ServerEndpoint 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@Component
@Service
@ServerEndpoint("/connect/{sid}")
@Slf4j
public class WebSocketServer {
    //静态变量，记录总共连接数，应该线程安全
    private static int onlineCount = 0;
    //存放每个WebSocket链接
    private static CopyOnWriteArraySet<WebSocketServer> socketServers = new CopyOnWriteArraySet<>();
    //获取客户端Session
    private Session session;
    //连接用户sid，通过sid标识用户
    private String sid;

    /**
     * @OnOpen 连接成功调用方法
     */
    @OnOpen
    public void connectSuccess(Session session, @PathParam("sid") String sid) {
        this.sid = sid;
        this.session = session; //获取会话
        socketServers.add(this); //添加链接进连接池
        addOnlineCount();
        log.info("用户UID：" + sid + "已连接");
    }

    /**
     * @OnClose 关闭连接调用方法
     */
    @OnClose
    public void connectClose() {
        socketServers.remove(this); //删除连接池元素
        subOnlineCount(); //连接数减一
        log.info("用户：" + this.sid + "断开连接");
    }

    /**
     * @OnMessage 收到客户端消息后
     */
    @OnMessage
    public void ConnectReceive(String message) {
        log.info("收到来至用户 " + this.sid + " 消息：" + message);
        sendMessage(message);
    }

    /**
     * @OnError 连接出错调用
     */
    @OnError
    public void ConnectError(Session session, Throwable error) {
        log.error(session.getId() + "连接错误: " + error.getMessage());
    }

    /**
     * 通过服务器给另一个用户发送信息
     */
    public static boolean sendMessageTo(String sid, String message) {
        boolean flag = false;
        for (WebSocketServer server : socketServers) {
            if (server.sid.equals(sid)) {
                log.info("发送信息给: " + server.sid);
                server.sendMessage(message);
                flag = true;
            }
        }
        return flag;
    }

    public static int sendMessageToAll(String message) {
        for (WebSocketServer server : socketServers) {
            server.sendMessage(message);
        }
        return onlineCount;
    }

    /**
     * 服务器发送信息
     */
    public void sendMessage(String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }


    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
}
